
//
//  LolViewController.m
//  XWZ_News_Work
//
//  Created by penngshi on 16/1/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LolViewController.h"

@interface LolViewController ()
@property (nonatomic , strong) UIImageView * imageV;
@property (nonatomic , strong) UIButton *returnButton;
@property (nonatomic, strong) AVPlayer *player;//播放器对象
@property (nonatomic , strong) NSString *urlStr;
@property (strong, nonatomic)  UIView *container; //播放器容器
@property (strong, nonatomic)  UIButton *playOrPause; //播放/暂停按钮
@property (strong, nonatomic)  UIProgressView *progress;//播放进度
@property (nonatomic , strong) UILabel *titleLabel;
@property(nonatomic) CGFloat brightness;
@property (nonatomic , strong) MBProgressHUD  *hub;
@end

@implementation LolViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  
//    [self requestData];
  
    self.view.backgroundColor = [UIColor whiteColor];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    self.hub.labelText = @"正在加载中......";
   
    [self setupUI];
      [self createSubView];
    [self.player play];
}
#pragma mark - 私有方法
-(void)setupUI{
    //创建播放器层
    AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:self.player];
    self.container = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    
    
    [self.container addGestureRecognizer:tap];
    [self.view addSubview:self.container];

    playerLayer.frame=self.container.frame;
    //    //playerLayer.videoGravity=AVLayerVideoGravityResizeAspect;//视频填充模式
    [self.container.layer addSublayer:playerLayer];
}

/**
 *  截取指定时间的视频缩略图
 *
 *  @param timeBySecond 时间点
 */

/**
 *  初始化播放器
 *
 *  @return 播放器对象
 */
-(AVPlayer *)player{
    if (!_player) {
        AVPlayerItem *playerItem=[self getPlayItem:0];
        _player=[AVPlayer playerWithPlayerItem:playerItem];
//        [self addProgressObserver];
        [self addObserverToPlayerItem:playerItem];
    }
    return _player;
}

/**
 *  根据视频索引取得AVPlayerItem对象
 *
 *  @param videoIndex 视频顺序索引
 *
 *  @return AVPlayerItem对象
 */

-(AVPlayerItem *)getPlayItem:(int)videoIndex{
   
    NSString *urlStr=[NSString stringWithFormat:@"http://hls.quanmin.tv/live/%@/playlist.m3u8", self.roomID];
    NSLog(@"^^^^^^^^^^^^^^^^^^^^^^%@", self.roomID);
    NSURL *url=[NSURL URLWithString: urlStr];
    AVPlayerItem *playerItem=[AVPlayerItem playerItemWithURL:url];
    return playerItem;
}
#pragma mark - 通知
/**
 *  添加播放器通知
 */
//-(void)addNotification{
//    //给AVPlayerItem添加播放完成通知
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
//}

-(void)removeNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  播放完成通知
 *
 *  @param notification 通知对象
 */
//-(void)playbackFinished:(NSNotification *)notification{
//    NSLog(@"视频播放完成.");
//}

#pragma mark - 监控
/**
 *  给播放器添加进度更新
 */
//-(void)addProgressObserver{
//    AVPlayerItem *playerItem=self.player.currentItem;
//    UIProgressView *progress=self.progress;
//    //这里设置每秒执行一次
//    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//        float current=CMTimeGetSeconds(time);
//        float total=CMTimeGetSeconds([playerItem duration]);
////        NSLog(@"当前已经播放%.2fs.",current);
//        if (current) {
//            [progress setProgress:(current/total) animated:YES];
//        }
//    }];
//}

/**
 *  给AVPlayerItem添加监控
 *
 *  @param playerItem AVPlayerItem对象
 */
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
}
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}
/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
//    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay){
            [self.hub hide:YES];
//            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        [self.hub show:YES];
//        NSArray *array=playerItem.loadedTimeRanges;
//        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
//        float startSeconds = CMTimeGetSeconds(timeRange.start);
//        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
//        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
//        NSLog(@"共缓冲：%.2f",totalBuffer);
        //
    }
}

#pragma mark - UI事件
/**
 *  点击播放/暂停按钮
 *
 *  @param sender 播放/暂停按钮
 */
- (void)playClick:(UIButton *)sender {
    //    AVPlayerItemDidPlayToEndTimeNotification
    //AVPlayerItem *playerItem= self.player.currentItem;
    if(self.player.rate == 0){ //说明时暂停
        [sender setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
        [self.player play];
    }else if(self.player.rate==1){//正在播放
        [self.player pause];
        [sender setImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
    }
}



- (void)createSubView
{

    self.imageV = [UIImageView new];
     self.imageV.userInteractionEnabled = YES;
    self.imageV.backgroundColor = [UIColor blackColor];
    self.imageV.alpha = 0.5;

    [self.container addSubview:self.imageV];
    
    [self.imageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.mas_equalTo(@0);
        make.height.mas_equalTo(@50);
        make.width.mas_equalTo(SCREEN_HEIGHT);
    }];
    
    self.titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 0, SCREEN_HEIGHT - 150, 50)];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.titleRoom;
    self.titleLabel.textColor = [UIColor whiteColor];
    [self.imageV addSubview:self.titleLabel];
    
    
 [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    self.returnButton = [UIButton new];
//    self.returnButton.backgroundColor = [UIColor whiteColor];
    [self.returnButton setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [self.imageV addSubview:self.returnButton];
    [self.returnButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo (@10);
        make.top.equalTo(@0);
        make.height.equalTo(@40);
        make.width.equalTo(@40);
    }];
    [self.returnButton addTarget:self action:@selector(returnButtonAction) forControlEvents:UIControlEventTouchUpInside];
   
    [UIScreen mainScreen].brightness = 0.1;
}
- (void)tapAction
{
    self.imageV.frame = CGRectMake(0, 0, SCREEN_WIDTH, 50) ;
}
- (void)timerFired
{
    self.imageV.frame = CGRectMake(0, -50, SCREEN_WIDTH, 50) ;
}

- (void)returnButtonAction
{
       self.player.rate = 0;
    [self dismissViewControllerAnimated:YES completion:^{
        
       
    }];
    
}
//当前是否支持转屏
- (BOOL)shouldAutorotate
{
    return YES;
}

// 当前支持的转屏幕方向
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeRight;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
